package com.herui.iot.ui.report;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.herui.sdyu_lib.base.FragmentDirectionAnim;
import com.herui.sdyu_lib.utils.StringUtils;
import com.herui.sdyu_lib.utils.ToastUtil;
import com.herui.sport_care.R;
import com.herui.sport_care.data.check.DeviceInfo;
import com.herui.sport_care.data.eval.BetaSchemeType;
import com.herui.sport_care.data.report.EvaluatorAppEvaluationReportResponse;
import com.herui.sport_care.data.report.ReportUser;
import com.herui.sport_care.data.report.TrendData;
import com.herui.sport_care.ui.BaseSportFragment;
import com.herui.sport_care.ui.evaluation.execute.EvalChoseFragment;
import com.herui.sport_care.ui.evaluation.execute.PowerExecuteFragment;
import com.herui.sport_care.ui.evaluation.execute.QuietCheckFragment;
import com.herui.sport_care.ui.evaluation.execute.TreadmillExecuteFragment;
import com.herui.sport_care.ui.view.ReportLineChartView;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 综合报告详情
 */
public class AllReportDetailFragment extends BaseSportFragment {

    @BindView(R.id.view_before)
    LinearLayout view_before;
    @BindView(R.id.view_test)
    LinearLayout view_test;
    @BindView(R.id.view_after)
    LinearLayout view_after;
    @BindView(R.id.edit_suggest)
    EditText edit_suggest;

    @BindView(R.id.mDoubleLineChar)
    LineChart mDoubleLineChar;
    ReportLineChartView reportLineChartView;

    private ReportUser reportUser;

    private Map<String, EditText> editTextMap = new HashMap<>();

    ReportPresenter reportPresenter;

    public static AllReportDetailFragment newInstance(ReportUser reportUser) {
        AllReportDetailFragment fragment = new AllReportDetailFragment();
        fragment.reportUser = reportUser;
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public AllReportDetailFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        setTitle("综合评估报告-" + reportUser.getBeEvaluatedName());

        reportPresenter = new ReportPresenter(reportView);

        return view;
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_all_report_detail;
    }

    @Override
    public void initParam() {
        reportLineChartView = new ReportLineChartView(mDoubleLineChar);
        reportLineChartView.init();

        reportPresenter.getEvaluationReportAll((long) reportUser.getId());
        reportPresenter.getTrendData((long) reportUser.getBetaDataId());
//        initData(new EvaluatorAppEvaluationReportResponse());
    }

    @OnClick({R.id.btn_edit})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_edit:

                Map<String, Object> map = new HashMap<>();
                map.put("beEvaluatedId", reportUser.getBeEvaluatedId());
                map.put("evaluationSchemeId", reportUser.getId());

                for (String key: editTextMap.keySet()){
                    EditText editText = editTextMap.get(key);
                    String s = editText.getText().toString();
                    if (!StringUtils.isEmpty(s)){
                        map.put(key, s);
                    }
                }
                String s = edit_suggest.getText().toString();
                if (!StringUtils.isEmpty(s)){
                    map.put("testsSuggest", s);
                }
                reportPresenter.updateEvaluationReport(map);
            default:
                break;
        }
    }

    private List<DataInfo> beforeDataInfos = new LinkedList<>();
    private List<DataInfo> testDataInfos = new LinkedList<>();
    private List<DataInfo> afterDataInfos = new LinkedList<>();

    private void initData(EvaluatorAppEvaluationReportResponse response) {
        beforeDataInfos.add(new DataInfo("静息心率", response.getQuiescentHr() + "", 0));
        beforeDataInfos.add(new DataInfo("静息心电说明", response.getQuiescentEcgExplain(), 1));
        beforeDataInfos.add(new DataInfo("静息血压",
                response.getQuiescentSbp() + "/" + response.getQuiescentSbp() + "mmhg(高压/低压)", 0));
        beforeDataInfos.add(new DataInfo("血氧饱和度", response.getQuiescentBloodOxygen() + "%", 0));
        beforeDataInfos.add(new DataInfo("不适症状", response.getQuiescentUncomfortableSymptom() + ""
                , 0));
        beforeDataInfos.add(new DataInfo("用药情况", response.getMedicationSituation() + "", 0));

        testDataInfos.add(new DataInfo("测试方案", response.getBetaSchemeSynopsis(), 0));
        testDataInfos.add(new DataInfo("最大摄氧量", response.getTestingMaximumOxygenUptake(), 1));
        testDataInfos.add(new DataInfo("测试结果分级", response.getBetaResultLevel(), 0));

        afterDataInfos.add(new DataInfo("第一次血压",
                response.getRecoverOneSbp() + "/" + response.getRecoverOneDbp() + "mmhg(高压/低压)",
                0));
        afterDataInfos.add(new DataInfo("即刻血氧", response.getRecoverBloodOxygen() + "%", 0));
        afterDataInfos.add(new DataInfo("第二次血压",
                response.getRecoverTwoSbp() + "/" + response.getRecoverTwoDbp() + "mmhg(高压/低压)",
                0));
        afterDataInfos.add(new DataInfo("恢复6min血压",
                response.getRecoverThreeSbp() + "/" + response.getRecoverthreeDbp() + "mmhg" +
                        "(高压/低压)", 0));
        afterDataInfos.add(new DataInfo("运动负荷心电", response.getExerciseLoadEcg(), 1));
        afterDataInfos.add(new DataInfo("恢复心电说明", response.getRecoverEcgExplain(), 1));
        afterDataInfos.add(new DataInfo("最大心率", response.getRecoverOneSbp(), 0));
        afterDataInfos.add(new DataInfo("恢复1min心率", response.getRecoverOneMinuteHr() + "", 0));
        afterDataInfos.add(new DataInfo("恢复2min心率", response.getRecoverTwoMinuteHr() + "", 0));
        afterDataInfos.add(new DataInfo("自觉最大用力", response.getRpe() + "", 0));
        afterDataInfos.add(new DataInfo("不适症状", response.getRecoverUncomfortableSymptom(), 1));


        initUi();
    }

    private void initUi() {

        LinearLayout[] linearLayouts = {view_before, view_test, view_after};

        for (int i = 0; i < linearLayouts.length; i++) {
            LinearLayout linearLayout = linearLayouts[i];
            linearLayout.removeAllViews();

            LinearLayout.LayoutParams params =
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
            LayoutInflater inflater = LayoutInflater.from(baseActivity);

            List<DataInfo> dataInfos = null;
            int item = R.layout.item_all_detail_before_user;

            int color = 0;
            switch (i) {
                case 0:
                    dataInfos = beforeDataInfos;
                    color = 0x8063e6be;
                    break;
                case 1:
                    dataInfos = testDataInfos;
                    color = 0x8066d9e8;
                    break;
                case 2:
                    dataInfos = afterDataInfos;
                    color = 0x80ff5733;
                    break;
            }

            for (int j = 0; j < dataInfos.size(); j++) {
                int c = 0xffffffff;
                if (j % 2 == 0) {
                    c = color;
                }
                DataInfo dataInfo = dataInfos.get(j);
                View layout = inflater.inflate(item, null);
                linearLayout.addView(layout, params);

                TextView titleTextView = layout.findViewById(R.id.tv_detail_number);
                titleTextView.setText(dataInfo.key);
                titleTextView.setBackgroundColor(c);

                TextView unitTextView = layout.findViewById(R.id.tv_detail_group);
                unitTextView.setBackgroundColor(c);
                EditText editText = layout.findViewById(R.id.et_detail_group);
                editText.setBackgroundColor(c);
                if (dataInfo.type == 0) {
                    unitTextView.setText(dataInfo.value.toString());
                    editText.setVisibility(View.GONE);
                } else {
                    editText.setText(dataInfo.value.toString());
                    unitTextView.setVisibility(View.GONE);
                    switch (dataInfo.key){
                        case "静息心电说明":
                            editTextMap.put("quiescentEcgExplain", editText);
                            break;
                        case "运动负荷心电":
                            editTextMap.put("recoverEcgExplain", editText);
                            break;
                        case "恢复心电说明":
                            editTextMap.put("recoverEcgExplain", editText);
                            break;
                        case "最大摄氧量":
                            editTextMap.put("testingMaximumOxygenUptake", editText);
                            break;
                        case "不适症状":
                            editTextMap.put("recoverUncomfortableSymptom", editText);
                            break;
                    }
                }

            }
        }

    }

    ReportPresenter.View reportView = new ReportPresenter.View() {
        @Override
        public void onEvaluatorAppEvaluationReportResponse(EvaluatorAppEvaluationReportResponse resp) {
            initData(resp);
        }

        @Override
        public void onUpdate() {
            ToastUtil.showMessage("更新报告成功");
        }

        @Override
        public void onTrendData(TrendData trendData) {
            List<List<Float>> powerTrendDataList = trendData.getPowerTrendDataList();
            List<List<Float>> heartRateTrendDataList = trendData.getHeartRateTrendDataList();
            List<List<Float>> calorieRateTrendDataList = trendData.getCalorieRateTrendDataList();

            List<Entry> leftEntries = new LinkedList<>();
            List<Entry> rightEntries = new LinkedList<>();

            for (int i = 0; i < heartRateTrendDataList.size(); i++) {
                List<Float> floats = heartRateTrendDataList.get(i);
                leftEntries.add(new Entry(floats.get(0) * 60, floats.get(1)));
            }

            if (powerTrendDataList != null) {
                if (powerTrendDataList.size() > 0) {
                    for (int i = 0; i < powerTrendDataList.size(); i++) {
                        List<Float> floats = powerTrendDataList.get(i);
                        rightEntries.add(new Entry(floats.get(0) * 60, floats.get(1)));
                    }
                } else {
                    rightEntries.add(new Entry(0, 0));
                }
                reportLineChartView.setData(leftEntries, rightEntries, "心率", "功率");
            } else {
                if (calorieRateTrendDataList.size() > 0) {
                    for (int i = 0; i < calorieRateTrendDataList.size(); i++) {
                        List<Float> floats = calorieRateTrendDataList.get(i);
                        rightEntries.add(new Entry(floats.get(0) * 60, floats.get(1)));
                    }
                } else {
                    rightEntries.add(new Entry(0, 0));
                }
                reportLineChartView.setData(leftEntries, rightEntries, "心率", "卡路里");
            }
        }
    };

    class DataInfo {
        public String key;
        public Object value;
        public int type;    // 0 textview 1 edittext

        public DataInfo(String key, Object value, int type) {
            this.key = key;
            this.value = value == null ? "" : value.toString();
            this.type = type;
        }
    }
}